package com.xwj.nio.netty.echoserver;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

/**
 * @author xwj
 * @date 2020/6/15
 */
@ChannelHandler.Sharable
public class NettyEchoServerHandler extends ChannelInboundHandlerAdapter {
    public static final NettyEchoServerHandler INSTANCE = new NettyEchoServerHandler();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
        ByteBuf in = (ByteBuf) msg;
        // 读取数据
        int len = in.readableBytes();
        byte[] arr = new byte[len];
        // Java不能直接访问Direct ByteBuf内部的数据，必须先通过getBytes、readBytes等方法，将数据读入Java数组中，然后才能继续在数组中进行处理
        in.getBytes(0, arr);
        System.out.println("收到消息：" + new String(arr, "UTF-8"));
        // 写回数据
        // 如果上一步使用的readBytes，那么这一步就不能直接将msg写回了，因为数据已经被readBytes读完了
        ChannelFuture f = ctx.writeAndFlush(msg);
        System.out.println("refCnt写回前：" + ((ByteBuf) msg).refCnt());
        f.addListener(future -> {
            System.out.println("refCnt写回后：" + ((ByteBuf) msg).refCnt());
        });
    }
}
